//
//  YZFetterConfigViewController.swift
//  YZFetter
//
//  Created by 康凯 on 2017/7/17.
//  Copyright © 2017年 康凯. All rights reserved.
//

import UIKit
import PKHUD
import CoreBluetooth

let titleArr: [String] = ["卡号", "短信号码", "IP地址", "端口号", "通信模式", "自动唤醒时长"]

// 配置界面
class YZFetterConfigViewController: KBaseViewController {

    var configCharacteristic: CBCharacteristic!
    let blueToothManager: YZBlueToothManager = YZBlueToothManager.shareInstances
    
    fileprivate var numberField: UITextField!
    var number: String!
    
    fileprivate var SMSField: UITextField!
    var SMS: String!
    
    fileprivate var IPField: UITextField!
    var ip: String!
    
    fileprivate var portField: UITextField!
    var port: String!
    
    fileprivate var wakeField: UITextField!
    var wakeInterval: String!
    
    var modeNum: String!
    
    
    private var inputArr: [UITextField] = []
    private var modeBtnArr: [UIButton] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        subViewInit()
    }

    override func viewWillAppear(_ animated: Bool) {
        numberField.text = number ?? "18893702601"
        SMSField.text = SMS ?? "18084825752"
        IPField.text = ip ?? "192.168.0.0"
        portField.text = port ?? "1580"
        wakeField.text = wakeInterval ?? "2"
        
        for modeBtn in modeBtnArr {
            modeBtn.titleLabel?.text == (modeNum as NSString).substring(to: 2) ? (modeBtn.isSelected = true) : (modeBtn.isSelected = false)
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    // MARK:- Customer Func
    func subViewInit() {
        title = "配置"
        view.backgroundColor = UIColor.white
        self.navigationItem.leftBarButtonItem?.tintColor = themeColor
        
        // 订阅断开连接的通知
        NotificationCenter.default.addObserver(self, selector: #selector(YZFetterConfigViewController.pop), name: NSNotification.Name(rawValue: peripherDisConnected), object: nil)

        let rightBtn = UIBarButtonItem.init(title: "完成", style: .done, target: self, action: #selector(YZFetterConfigViewController.configComplete))
        self.navigationItem.rightBarButtonItem = rightBtn
        self.navigationItem.rightBarButtonItem?.tintColor = themeColor
        
        for index in 0..<titleArr.count {
            let contentView = UIView()
            contentView.frame = CGRect.init(x: 0, y: CGFloat(index) * itemHeight + 64 + 10, width: kScreen_Width, height: itemHeight - 1)
            contentView.backgroundColor = UIColor.clear
            view.addSubview(contentView)
            
            let titleLabel = UILabel()
            titleLabel.frame = CGRect.init(x: 5, y: 0, width: 100, height: contentView.height)
            titleLabel.text = titleArr[index]
            titleLabel.backgroundColor = UIColor.clear
            titleLabel.textColor = UIColor.init(rgbHex: "959599")
            titleLabel.font = k_labelFont
            titleLabel.textAlignment = .left
            contentView.addSubview(titleLabel)
            
            if titleArr[index] == "通信模式" {
                let btnSep: CGFloat = 5.0
                let btnWidth = (contentView.width - titleLabel.width - 4 * btnSep) / 3
                // 三个按钮
                for i in 0..<3 {
                    let modeBtn = UIButton()
                    modeBtn.frame = CGRect.init(x: titleLabel.right + CGFloat(i) * (btnSep + btnWidth), y: 0, width: btnWidth, height: contentView.height)
                    modeBtn.titleLabel?.font = k_labelFont
                    modeBtn.setTitle(["流量", "短信", "混合"][i], for: .normal)
                    modeBtn.setTitleColor(UIColor.darkText, for: .normal)
                    modeBtn.setImage(#imageLiteral(resourceName: "choose_u"), for: .normal)
                    modeBtn.setImage(#imageLiteral(resourceName: "choose"), for: .selected)
                    modeBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0)
                    modeBtn.addTarget(self, action: #selector(YZFetterConfigViewController.btnSelected(btn:)), for: .touchUpInside)
                    modeBtn.backgroundColor = UIColor.clear
                    modeBtn.tag = i + 1
                    contentView.addSubview(modeBtn)
                    modeBtnArr.append(modeBtn)
                }
                
            }else {
                let contenInput = UITextField()
                contenInput.frame = CGRect.init(x: titleLabel.right, y: 5, width: contentView.width - titleLabel.width - 5 * 2, height: titleLabel.height - 10)
                contenInput.delegate = self
                contenInput.backgroundColor = UIColor.clear
                contenInput.textColor = UIColor.darkText
                contenInput.font = titleLabel.font
                contenInput.layer.borderColor = UIColor.lightGray.withAlphaComponent(0.5).cgColor
                contenInput.layer.borderWidth = 1.0
                contenInput.layer.cornerRadius = 3
                contenInput.textAlignment = .right
                contenInput.keyboardType = .decimalPad
                contenInput.tag = index
                contentView.addSubview(contenInput)
                inputArr.append(contenInput)
                switch index {
                    case 0:     numberField = contenInput
                    case 1:     SMSField    = contenInput
                    case 2:     IPField     = contenInput
                    case 3:     portField   = contenInput
                    case 5:     wakeField   = contenInput
                    default:    break
                }
            }
            
        }
    }
    
    // 返回到上一级
    func pop() {
        self.navigationController?.popViewController(animated: true)
    }
    
    // MARK:- Customer Func
    func configComplete() {
        view.endEditing(true)
        if checkEmptyInput() {
            blueToothManager.write(data: changeToData(), for: configCharacteristic)
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    func changeToData() -> Data {
        var byte: [UInt8] = []
        
        // 先 IP地址
        let IPArr = IPField.text?.components(separatedBy: ".")
        for ipSubStr in IPArr! {
            byte.append(UInt8(ipSubStr)!)
        }
        
        // 端口
        let portNum = Int(portField.text!)
        
        byte.append(UInt8(portNum! % 256))
        byte.append(UInt8(portNum! / 256))
        
        // 告警号码
        let smsNumber = SMSField.text! as NSString
        for index in 0...smsNumber.length / 2 {
            if index == 5 {
               byte.append(UInt8(smsNumber.substring(with: NSRange.init(location: index * 2, length: 1)))!)
            } else {
                byte.append(UInt8(smsNumber.substring(with: NSRange.init(location: index * 2, length: 2)))!)
            }
        }
        
        // 通信模式，状态号码
        for modeBtn in modeBtnArr {
            if modeBtn.isSelected {
                byte.append(UInt8(modeBtn.tag))
            }
        }
        
        // 自动唤醒时长
        byte.append(UInt8(wakeField.text!)!)
        
        // 卡号
        let phoneNumber = numberField.text! as NSString
        for index in 0...phoneNumber.length / 2 {
            if index == 6 {
                break
//                byte.append(UInt8(phoneNumber.substring(with: NSRange.init(location: index * 2, length: 1)))!)
            } else {
                byte.append(UInt8(phoneNumber.substring(with: NSRange.init(location: index * 2, length: 2)))!)
            }
        }
        return Data.init(bytes: byte)
    }
    
    // 检查有没有项目没有输入
    func checkEmptyInput() -> Bool {
        for inputView in inputArr {
            if (inputView.text?.isEmpty)! {
                show(err: "请输入\(titleArr[(inputView.tag)])")
                return false
            }
        }
        return checkRightInput()
    }
    
    // 检查输入的格式
    func checkRightInput() -> Bool {
        if numberField.text?.characters.count != 12 {
            show(err: "卡号不足12位")
            return false
        }
        
        if SMSField.text?.characters.count != 11 {
            show(err: "短信号码不足11位")
            return false
        }
        
        if (IPField.text?.characters.count)! <= 15{
            let ipStrComponents = IPField.text?.components(separatedBy: ".")
            if ipStrComponents?.count != 4 {
                show(err: "IP格式不正确")
                return false
            }
        }else {
            show(err: "输入正确的IP")
            return false
        }
        
        return true
    }
 
    // 设置选中的模式
    func btnSelected(btn: UIButton) {
        for button in modeBtnArr {
            button.isSelected = false
        }
        btn.isSelected = true
    }
    
    // 显示提示信息
    func show(err msg: String) {
        HUD.flash(.labeledError(title: "错误", subtitle: msg), delay: 1.50)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
}

extension YZFetterConfigViewController: UITextFieldDelegate {
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        textField.layer.borderColor = themeColor.withAlphaComponent(0.5).cgColor
        return true
    }
    
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        textField.layer.borderColor = UIColor.lightGray.withAlphaComponent(0.5).cgColor
        return true
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        switch textField {
        case numberField:
            if (numberField.text?.characters.count)! >= 10  {
                numberField.text = (numberField.text! as NSString).substring(to: 10)
            }
        case SMSField:
            if (SMSField.text?.characters.count)! >= 10  {
                SMSField.text = (SMSField.text! as NSString).substring(to: 10)
            }
        case IPField:
            if (IPField.text?.characters.count)! >= 14 {
                IPField.text = (IPField.text! as NSString).substring(to: 14)
            }
        case portField :
            if (portField.text?.characters.count)! >= 4 {
                portField.text = (portField.text! as NSString).substring(to: 4)
            }
        case wakeField:
            if (wakeField.text?.characters.count)! >= 1 {
                wakeField.text = (wakeField.text! as NSString).substring(to: 1)
            }
        default:
            break
        }
        
        return true
    }
}
